#include "crc32.h"

namespace umtl
{
	unsigned int getFileCRC(FILE *s) {
		unsigned char buf [32768];
		unsigned int CRC = 0;
		size_t len;
		while ( (len = fread(buf, 1, sizeof(buf), s)) != NULL )
			CRC = calcCRC(buf, (unsigned int) len, CRC);
		return CRC;
	}

	unsigned int calcCRC(const unsigned char *mem, unsigned int size, unsigned int CRC) {
		unsigned int table[256];
		CRC = ~CRC;
		makeCRCtable(table, 0xEDB88320);
		while(size--)
			CRC = table[(CRC ^ *(mem++)) & 0xFF] ^ (CRC >> 8);
		return ~CRC;
	}

	void makeCRCtable(unsigned int *table, unsigned int id) {
		unsigned int i, j, k;
		for(i = 0; i < 256; ++i) {
			k = i;
			for(j = 0; j < 8; ++j) {
				if (k & 1) k = (k >> 1) ^ id;
				else k >>= 1;
			}
			table[i] = k;
		}
	}
}